<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport"
    content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <title>直播</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      -webkit-tap-highlight-color: transparent;
    }
  </style>
  <link rel="stylesheet" href="./css/video.css" />
  <link rel="stylesheet" href="./css/video.min.css" />
</head>

<body>
  <div id="app" style="display: none;">
    <div id="live_top_box">
      <div id="videobox">
        <video id="my-player" class="video-js vjs-big-play-centered live" controls preload="auto" :poster="postImg"
          x5-video-player-fullscreen="true" x5-playsinline playsinline webkit-playsinline
          style="width: 100%; height: 100%; object-fit: cover;" muted autoplay>
          <source :src="videourl" type="application/x-mpegURL" v-if="isLive" />
          <source :src="currentSource" v-else />
        </video>
        <p class="hold" v-if="(status==1 || status==3) && complete==false && isReady==true">
          {{status==1?"直播未开始":"直播结束,观看回放"}}
        </p>
        <p class="title" v-if="status==1">
          <span>直播开始时间</span>
          <span>{{liveInfo.startTime}}</span>
        </p>

        <!-- <div class="live_share" v-show="likeIcon && isReady==true">
          <div class="collction" @click="changeCollctionState">
            <img :src="like[Number(join)]" alt="" />
          </div>
        </div> -->
      </div>

      <section :class="status==1?'hasletter contain_info':'contain_info'">
        <p class="contain_title">{{liveInfo.title}}</p>
        <!-- <span v-if="status==1">直播预告</span> -->
      </section>
      <div class="kong"></div>
    </div>

    <nav class="live_tab">
      <div @click="selectTab(0)" :class='activeindex==0?"active":""'>
        直播简介
      </div>
      <div @click="selectTab(1)" :class='activeindex==1?"active":""'>
        互动
      </div>
      <div @click="selectTab(2)" :class='activeindex==2?"active":""'>
        更多
      </div>

      <i class="left"></i>
    </nav>

    <section class="advance max_height" v-show="activeindex==0">
      <div v-html="advanceInfo.body"></div>
    </section>

    <section class="live_card max_height" v-show="activeindex==2">
      <div class="card" v-for="(item, index) in relations" :key="index" @click="jumpRecommend(item)">
        <img :src="item.launchImage && item.launchImage.fileUrl" alt="" />
        <div>
          <p>{{item.title || '加载中'}}</p>
          <p>{{item.startTime || '2020.2.14'}}</p>
        </div>
        <span class="card_state">
          <div v-if="item.status==2"></div>
          <span>{{mocardState(item) || '直播中'}}</span>
        </span>
      </div>
    </section>

    <section class="hudong max_height" v-show="activeindex==1">
      <div v-for="(item, index) in list" :key="index">
        <img :src="item.avatar" alt="" />
        <div>
          <h3>{{item.userName}}</h3>
          <div>{{item.intro}}</div>
        </div>
      </div>
    </section>

    <div class="toast" v-show="toast" @click.stop>
      未登录
    </div>

    <div class="bottom_in" v-show="activeindex==1">
      <input type="text" @focus="inputfoucs=true" @blur="inputfoucs=false" style="padding-left: 0.4rem;"
        placeholder="说点什么吧" v-model="text" />
      <button @click="send">发送</button>
    </div>

    <div class="toast" v-show="toastSwitch">
      还未登录
    </div>
  </div>
</body>
<script>
  (function () {
    let doc = document.documentElement,
      resizeEvt =
        "orientationchange" in window ? "orientationchange" : "resize";
    function changeFontSize() {
      let clientWidth = doc.offsetWidth,
        scale = clientWidth / 750;
      doc.style.fontSize = scale * 100 + "px";
    }
    if (!doc.addEventListener) return;
    window.addEventListener(resizeEvt, changeFontSize); // 监听窗口变化或横屏时
    document.addEventListener("DOMContentLoaded", changeFontSize);
  })();
</script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="./js/video.min.js"></script>
<script src="./js/videojs-contrib-hls.min.js"></script>
<script src="./js/videojs-flash.min.js"></script>
<script src="https://res.wx.qq.com/open/js/jweixin-1.3.0.js"></script>
<script src="./js/jq.js"></script>
<script>
  class Slide {
    constructor(element, range) {
      this.element = element; //目标DOM元素
      this.range = range || 20; //滑动距离，大于或者等于这个值时才算有效的滑动
      this.moving = false;
      this.startX = 0;
      this.startY = 0;
      this.endX = 0;
      this.endY = 0;
    }

    slideUp(callback) {
      this.slide("up", callback);
    }

    slideDown(callback) {
      this.slide("down", callback);
    }

    slideLeft(callback) {
      this.slide("left", callback);
    }

    slideRight(callback) {
      this.slide("right", callback);
    }

    slide(direction, callback) {
      this.element.addEventListener(
        "touchstart",
        (e) => this.touchstart(e),
        false
      );
      this.element.addEventListener(
        "touchmove",
        (e) => this.touchmove(e),
        false
      );
      this.element.addEventListener(
        "touchend",
        (e) => this.touchend(direction, callback, e),
        false
      );
    }

    touchstart(e) {
      let touches = e.touches[0];
      let { clientX, clientY } = touches;
      [this.startX, this.startY] = [clientX, clientY];
      this.moving = false;
    }

    touchmove(e) {
      this.moving = true;
    }

    touchend(direction, callback, e) {
      if (!this.moving) {
        return;
      }
      let cb = (...args) =>
        typeof callback === "function" && callback(...args);
      let touches = e.changedTouches[0];
      let { clientX, clientY } = touches;
      [this.endX, this.endY] = [clientX, clientY];
      let distanceX = this.startX - this.endX;
      let distanceY = this.startY - this.endY;
      let action =
        Math.abs(distanceX) >= Math.abs(distanceY) ? "left-right" : "up-down";
      if (action === "left-right") {
        if (distanceX < -this.range) {
          direction === "right" && cb();
        } else if (distanceX > this.range) {
          direction === "left" && cb();
        }
      } else if (action === "up-down") {
        if (distanceY < -this.range) {
          direction === "down" && cb();
        } else if (distanceY > this.range) {
          direction === "up" && cb();
        }
      }
    }
  }

  let baseUrl = "https://api.77du.net/ciff/miniappapi"; //环境一
  document.getElementById("app").style.display = "block";
  function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURI(r[2]);
    return null;
  }

  var getheader = {
    token: getQueryString("token"),
    "X-Requested-With": "XMLHttpRequest",
    Accept: "application/json",
    "Content-Type": "application/json; charset=UTF-8",
    r: new Date().getTime(),
  };
  var otherHeader = {
    token: getQueryString("token"),
    "X-Requested-With": "XMLHttpRequest",
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
    r: new Date().getTime(),
  };
  let vm = new Vue({
    el: "#app",
    data() {
      return {
        id: getQueryString("id"),
        token: getQueryString("token"),
        liveInfo: {},
        videourl: {},
        play: {},
        status: null,
        activeindex: 0,
        isLive: false,
        relations: [], //关联的直播信息
        advanceInfo: {}, //直播的预告信息
        vods: [], //点播的id数组,在非直播的时候使用
        videoList: [], //点播回放的视频地址列表
        currentVideoIndex: 0,
        hasError: false, //直播是否有错误、
        isReady: true, //回放的视频阿里云是否有准备好
        complete: false,
        join: 0,
        like: [`./img/kong.png`, `./img/dzaixin.png`],
        likeIcon: true,
        toast: false, //消息提示
        palyvoice: true,
        inputfoucs: false,
        text: "",
        list: [], //平路列表
        total: 10,
        index: 1,
        toastSwitch: false,
      };
    },
    watch: {
      status: function (newvalue) {
        if (newvalue == 1) {
          //直播未开始
          this.$nextTick(() => {
            document.querySelector(".vjs-big-play-button").style.display =
              "none";
          });
        }
      },
    },
    computed: {
      mocardState() {
        return (item) => {
          if (item.status == 1) {
            return "直播预告";
          } else if (item.status == 2) {
            return "直播中";
          } else if (item.status == 3) {
            return "直播结束";
          }
        };
      },
      //当前回放视频的地址
      currentSource() {
        if (this.vods.length == 0) return "";
        if (this.videoList.length == 0) return "";
        return this.videoList[this.currentVideoIndex].fileUrl;
      },
      //海报图
      postImg() {
        if (
          this.liveInfo &&
          this.liveInfo.mainImage &&
          this.liveInfo.mainImage.fileUrl
        ) {
          return this.liveInfo.mainImage.fileUrl;
        } else {
          return "";
        }
      },
    },
    methods: {
      //播放器的初始操作
      initVideo() {
        // document.getElementById("videoMP4").src = this.videourl;
        this.play = videojs("my-player");
        // document.querySelector(".vjs-big-play-button").style.display = "none";
        this.play.on("playing", () => {
          this.likeIcon = false;
        });
        this.play.on("error", (err) => {
          console.log("err", err);
          this.hasError = true;
        });
      },
      //直播间信息
      getLiveInfo() {
        return new Promise((reslove, reject) => {
          $.ajax({
            url: baseUrl + `/live/${this.id}`,
            type: "get",
            headers: getheader,
            success: (res) => {
              if (res.code === "000000") {
                this.liveInfo = res.data;
                this.relations = this.liveInfo.relations; //推荐的视频
                this.join = this.liveInfo.join; //是否收藏
                this.vods = this.liveInfo.vods || []; //回放的视频信息
                console.log(res);
                document.title = res.data.title;
                this.status = this.liveInfo.status; //直播间的状态
                reslove(this.status);
              }
            },
          });
        });
      },
      // 直播播放流
      getvideoFil() {
        return new Promise((reslove, reject) => {
          $.ajax({
            url: baseUrl + `/live/stream/playurl?id=${this.id}`,
            headers: getheader,
            success: (res) => {
              if (res.code == "000000") {
                reslove(res);
              } else {
                reject(res);
              }
            },
          });
        });
      },
      //获取直播预告信息
      getAdvance(id) {
        return new Promise((reslove, reject) => {
          $.ajax({
            url: baseUrl + "/live/foreshow/" + id,
            headers: getheader,
            type: "get",
            success: (res) => {
              reslove(res);
            },
            fail: (err) => {
              reject(err);
            },
          });
        });
      },
      //获取回放视频的信息
      getPlayBackVideo(videoId) {
        return new Promise((reslove, reject) => {
          $.ajax({
            url: baseUrl + "/vod/video/play/url?videoId=" + videoId,
            type: "get",
            success: (res) => {
              reslove(res);
            },
          });
        });
      },
      //初始化直播
      async initPage() {
        //直播间信息
        let status = await this.getLiveInfo();

        status == "2" ? (this.isLive = true) : (this.isLive = false);
        //直播预告信息
        let res = await this.getAdvance(this.id);
        if (res.code == "000000") {
          this.advanceInfo = res.data;
        }
        //如果是直播,则直接播放
        if (this.isLive == true) {
          let res = await this.getvideoFil();
          this.videourl = res.data.m3u8 || res.data.fileUrl;
          this.$nextTick(() => {
            setTimeout(() => {
              this.complete = true;
              this.initVideo();
            }, 300);
          });
          return;
        }
        //如果没哟直播,则先获取直播的点播视频
        if (this.vods && this.vods.length > 0) {
          let res = await this.getPlayBackVideo(this.vods[0].playId);
          let data = res.data || {};
          console.log(data);
          this.videoList.push(data);
          setTimeout(() => {
            this.complete = true;
          }, 3000);
        } else {
          //阿里云回放视频还没有准备好
          this.isReady = false;
        }
        this.$nextTick(() => {
          setTimeout(() => {
            this.play = videojs("my-player");
            this.play.on("playing", () => {
              this.likeIcon = false;
            });

            this.play.on("canplay", () => {
              this.playstart();
              document.addEventListener(
                "WeixinJSBridgeReady",
                function () {
                  document.getElementById("my-player").play();
                },
                false
              );
            });
            this.play.on("ended", this.ended);
          }, 200);
        });
      },
      playstart() {
        this.play && this.play.play();
      },
      pause() {
        this.play && this.play.pause();
      },
      selectTab(index) {
        this.activeindex = index;
      },
      //相关推荐的跳转
      jumpRecommend(item) {
        wx.miniProgram.navigateTo({
          url: "/pages/live/live?id=" + item.id,
        });
      },
      //结束之后触发的事件
      async ended() {
        if (this.vods.length - 1 == this.currentVideoIndex) {
          return; //已经没有下一个视频了
        }
        let nextIndex = this.currentVideoIndex + 1;
        this.likeIcon = true;
        let res = await this.getPlayBackVideo(this.vods[nextIndex].playId);
        let data = res.data || {};
        this.videoList.push(data);
        this.currentVideoIndex++;
        //开始传入下一个视频
        this.play.src({ src: this.currentSource });
        this.$nextTick(() => {
          this.complete = true;
          this.playstart();
        });
      },
      //收藏该直播间
      likeLive() {
        return new Promise((reslove, reject) => {
          $.ajax({
            url: baseUrl + "/subject/favorite?subjectId=" + this.id,
            headers: getheader,
            type: "get",
            success: (res) => {
              reslove(res);
            },
            fail: (err) => {
              reject(err);
            },
          });
        });
      },
      //取消收藏的请求
      deleteLive() {
        return new Promise((reslove, reject) => {
          $.ajax({
            url: baseUrl + "/subject/favorite?subjectId=" + this.id,
            type: "DELETE",
            headers: otherHeader,
            success: (res) => {
              reslove(res);
            },
            fail: (err) => {
              reject(err);
            },
          });
        });
      },
      //收藏或者取消收藏该直播间
      async changeCollctionState() {
        if (!this.token) {
          this.toast = true;
          setTimeout(() => {
            this.toast = false;
          }, 1500);
          return;
        }
        if (this.join == 0) {
          let res = await this.likeLive();
          if (res.code === "000000") {
            this.join = 1;
          }
        } else {
          let res = await this.deleteLive();
          if (res.code === "000000") {
            this.join = 0;
          }
        }
      },
      //获取聊天记录
      getLiveCommlist(id) {
        // this.index = parseInt(this.total / 10);
        return new Promise((reslove, reject) => {
          $.ajax({
            url: baseUrl + "/live/comment",
            type: "get",
            headers: getheader,
            data: {
              index: this.index,
              size: 10,
              liveId: this.id,
            },
            success: (res) => {
              reslove(res);
            },
            fail: (err) => {
              reject(err);
            },
          });
        });
      },
      async initLiveChart() {
        let res = await this.getLiveCommlist(this.id);
        console.log(res);
        if (res.code == "000000") {
          let { content, total } = res.data;
          content = content.reverse();
          console.log(content);
          this.list.push(...content);
          this.$nextTick(() => {
            setTimeout(() => {
              $(".hudong").scrollTop(10000000);
            }, 300);
          });
        }
      },
      //发送直播间聊天
      sendLiveChart() {
        let param = {
          resourceId: this.id,
          intro: this.text,
        };
        getheader.r = new Date().getTime();
        return new Promise((relsove, reject) => {
          $.ajax({
            url: baseUrl + "/live/comment",
            type: "post",
            data: JSON.stringify(param),
            headers: getheader,
            success: (res) => {
              relsove(res);
            },
            fail: (err) => {
              reject(err);
            },
          });
        });
      },
      //发送消息评论
      async send() {
        if (!this.token) {
          this.toastSwitch = true;
          setTimeout(() => {
            this.toastSwitch = false;
            // wx.miniProgram.switchTab({
            //   url: "/pages/my/my",
            // });
            wx.miniProgram.redirectTo({
              url: "/pages/login/login?type=1&id=" + this.id,
            });
          }, 2000);
          return;
        }
        let res = await this.sendLiveChart();
        if (res.code == "000000") {
          this.text = "";
          this.list.push(res.data);
          this.$nextTick(() => {
            setTimeout(() => {
              $(".hudong").scrollTop(10000000);
            }, 300);
          });
        } else if (res.code == "10003") {
          alert("请勿重复发消息");
        }
      },
    },
    created() {
      this.initPage();
      this.$nextTick(() => {
        // textheight=document.getElementsByClassName('.contain_info')[0]
        console.log(
          document.getElementsByClassName("contain_info")[0].offsetHeight
        );
        this.initLiveChart();
      });
    },
  });
  //滑动手势
  $(function () {
    // var docheight = $(".advance").scrollHeight()
    let artice = $(".advance");
    let live = $(".live_card");
    let hud = $(".hudong");
    let livebox = $("#live_top_box");
    let signa = $(".left");
    function down() {
      artice.height("calc(100vh - 7.15rem)");
      live.height("calc(100vh - 7.15rem)");
      hud.height("calc(100vh - 7.15rem)");
      livebox.animate({ height: "5.87rem" }, "fast");
      signa.hide();
    }
    artice.css(
      { position: "relative" },
      { left: 0 },
      { top: 0 },
      { zIndex: 999 }
    );
    live.css(
      { position: "relative" },
      { left: 0 },
      { top: 0 },
      { zIndex: 999 }
    );
    hud.css(
      { position: "relative" },
      { left: 0 },
      { top: 0 },
      { zIndex: 999 }
    );
    var time = null;
    artice.scroll(function (e) {
      // console.log((this.scrollTop / this.scrollHeight).toFixed(2));
      clearInterval(time);
      time = setTimeout(() => {
        if ((this.scrollTop / this.scrollHeight).toFixed(2) >= "0.30") {
          // alert(12121)
          livebox.animate({ height: "0px" }, "fast");
          artice.height("calc(100vh - 1.14rem)");
          live.height("calc(100vh - 1.14rem)");
          hud.height("calc(100vh - 1.14rem)");
          signa.show();
        } else {
          // alert('1111sssss')
          // down();
        }
      }, 300);
    });
    signa.on("click", function () {
      down();
    });
    let tab = document.querySelectorAll(".live_tab")[0];
    console.log(tab);
    let slide = new Slide(tab);
    slide.slideDown(() => {
      down();
    });
  });
</script>

</html>